<?php

class Application_Auth implements Application_Interface_Singleton {
    
    /**
     * @var Application_Auth
     */
    private static $_instance = null;
    
    /**
     * @return Application_Auth
     */
    public static function getInstance() {
        if(self::$_instance === null) {
            self::$_instance = new self;
        }
        return self::$_instance;
    }
    
    public function authenticate($login, $password) {
        //echo ',1.1,';
        $manager = epManager::instance();
        //echo '1.2,';
        $users = $manager->find('from BO_User where login = ? and password = ?', $login, $password);
        //echo '2,';
        if (count($users) == 1) {
            //echo '3.1,';
            $this->_login($users[0]);
            //echo '3.2,';
            return true;
        } else {
            //echo '3.3,';
            return false;
        }
    }
    
    private function _login($user) {
        Application_Registry_Session::getInstance()->loggedUser = $user;
    }
    
    public function logout() {
        Application_Registry_Session::getInstance()->loggedUser = null;
    }
    
    public function createUser($login) {
        if ($this->loginExists($login)) {
            throw new Application_Exception('Login '.$login.' already exists.');
        }
        $user = epManager::instance()->create('BO_User');
        $user->login = $login;
        return $user;
    }
    
    public function loginExists($login) {
        return (count(epManager::instance()->find('from BO_User where login = ?', $login)) > 0);
    }
    
    private function _getRequiredRoles($action) {
        $xpath = "//controller[@name='".$action->getControllerName()."']/action[@name='".$action->getActionName()."']/role | //controller[@name='".$action->getControllerName()."']/role";
        return array_unique((array)Application_Helper::getInstance()->getConfig('controllers')->xpath($xpath));
    }
    
    public function isReachable($action) {
        $requiredRoles = $this->_getRequiredRoles($action);
        if (empty($requiredRoles)) return true;
        $user = Application_Registry_Session::getInstance()->loggedUser;
        if (!isset($user)) return false;
        $userRoles     = $user->getRoles();
        if (empty($userRoles)) return false;
        return count(array_intersect($requiredRoles, $userRoles)) > 0;
    }
    
}

?>